import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/routes/routes.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/m3u8_download/local_server.dart';
import 'package:pornhub_app/utils/m3u8_download/m3u8_download_notify_state.dart';

import '../../assets/styles.dart';
import '../../utils/extension.dart';
import '../../utils/logger.dart';
import '../../utils/m3u8_download/m3u8_download_record.dart';
import '../../utils/m3u8_download/m3u8_downloader_manager.dart';
import '../image_view.dart';
import 'video_duration_cell.dart';
import 'video_type_banner.dart';

class VideoDownloadCell extends StatelessWidget {
  final M3u8DownloadRecord record;
  final double? height;

  VideoDownloadCell({super.key, required this.record, double? height})
      : height = 104.w;

  Widget _buildCover() => ImageView(
        src: record.cover,
        width: 182.w,
        height: height,
        borderRadius: Styles.borderRadius.m,
        fit: BoxFit.cover,
      );

  Widget _buildVideoType() => VideoTypeBanner(
        videoType: record.videoType,
        price: record.price,
        showFree: true,
      );

  Widget _buildPlayTime() => VideoDurationCell(playTime: record.playTime);

  Widget _buildLeading() => Stack(
        children: [
          _buildCover(),
          Positioned(top: 0, right: 0, child: _buildVideoType()),
          Positioned(bottom: 6.3, right: 5.7.w, child: _buildPlayTime()),
        ],
      );

  Widget _buildTitle() => Text(
        record.title ?? '',
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          color: Colors.white,
          fontSize: 12.w,
          fontWeight: FontWeight.w400,
        ),
      );

  Widget _buildProgressIndicator(double? value, {String? tips}) {
    String progress = '';
    if (value != null) {
      progress = '${(value * 100).toStringAsFixed(2)}%';
    }
    return ClipRRect(
      borderRadius: Styles.borderRaidus.m,
      child: Stack(
        children: [
          LinearProgressIndicator(
            backgroundColor: COLOR.color_666666,
            color: COLOR.hexColor("#DC143C"),
            minHeight: 10.w,
            value: value,
          ),
          Positioned.fill(
              child: Center(
            child: Text(
              tips ?? progress,
              style: TextStyle(
                color: Styles.color.whiteText,
                fontSize: Styles.fontSize.xxs,
              ),
            ),
          ))
        ],
      ),
    );
  }

  Widget _buildProgressSuccess() => _buildProgressIndicator(1.0);
  Widget _buildProgressWaiting() => _buildProgressIndicator(0.0, tips: '等待中');
  Widget _buildProgressFail() => _buildProgressIndicator(0.0, tips: '下载失败');

  Widget _buildProgress() {
    if (record.isError) {
      return _buildProgressFail();
    } else if (record.isSuccess) {
      return _buildProgressSuccess();
    }
    final notifier = M3u8DownloadManager.getNotifier(record.videoId);
    if (notifier == null) {
      logger.d('video download not registered');
      return const SizedBox.shrink();
    }
    return ValueListenableBuilder(
        valueListenable: notifier,
        builder: (context, value, _) {
          if (value.state.isNone) {
            // 不会到这里
            assert(false, 'state none in download page');
            return const SizedBox.shrink();
          } else if (value.state.isWaiting) {
            return _buildProgressWaiting();
          } else if (value.state.isDownloading) {
            return _buildProgressIndicator(value.progress);
          } else if (value.state.isSuccess) {
            return _buildProgressSuccess();
          } else {
            return _buildProgressFail();
          }
        });
  }

  Widget _buildTrailing() => Expanded(
        child: SizedBox(
          height: height,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildTitle(),
              _buildProgress(),
            ],
          ).paddingVertical(7.w),
        ).marginLeft(8.w),
      );

  void _tap() {
    if (record.isSuccess) {
      final url = LocalServer.remoteM3u82Local(videoId: record.videoId);
      Get.toComonVideoPlay(url: url);
    } else {
      Get.toPlayVideo(videoId: record.videoId);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        _buildLeading(),
        _buildTrailing(),
      ],
    ).onOpaqueTap(_tap);
  }
}
